package com.yupi.springbootinit.job.once;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.esdao.PostEsDao;
import com.yupi.springbootinit.model.dto.post.PostEsDTO;
import com.yupi.springbootinit.model.dto.post.PostQueryRequest;
import com.yupi.springbootinit.model.entity.Post;
import com.yupi.springbootinit.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 定时任务，只在项目启动时执行一次
 * 获取初始化的帖子数据（鱼皮的编程导航网站中的文章）
 *
 */
//todo 关闭注释则开启定时任务
//@Component
@Slf4j
public class FetchInitPostList implements CommandLineRunner {
    /**
     * 只需要让该类实现CommandLineRunner这个接口，然后实现接口里的run方法即可
     * 注意要把该类注册为bean，这样在项目启动时，这个类中的run方法就会执行一次
     */

    @Resource
    private PostService postService;


    @Override
    public void run(String... args) throws Exception {
        //构造请求与请求参数
        String json = "{\"current\":1,\"pageSize\":8,\"sortField\":\"createTime\",\"sortOrder\":\"descend\",\"category\":\"文章\",\"tags\":[],\"reviewStatus\":1}";
        String url = "https://www.code-nav.cn/api/post/search/page/vo";
        //发送请求，获取编程导航这个网站的文章数据
        String result = HttpRequest.post(url).body(json).execute().body();
        if (result == null){
            throw new RuntimeException("帖子接口请求失败");
        }

        //解析数据
        Map<String,Object> map = JSONUtil.toBean(result, Map.class);
        if (Integer.parseInt(map.get("code").toString()) != 0){
            throw new RuntimeException("数据解析异常");
        }
        JSONObject data = (JSONObject) map.get("data");
        if (data == null){
            throw new RuntimeException("数据解析异常");
        }
        JSONArray records = (JSONArray) data.get("records");
        if (records == null){
            throw new RuntimeException("数据解析异常");
        }

        List<Post> postList = new ArrayList<>();
        for (Object record : records) {
            JSONObject tempRecord = (JSONObject) record;
            Post post = new Post();
            post.setTitle(tempRecord.getStr("title"));
            post.setContent(tempRecord.getStr("content"));

            //获取文章标签:
            JSONArray tags = (JSONArray) tempRecord.get("tags");
            String tagJson = JSONUtil.toJsonStr(tags);
            post.setTags(tagJson);
            //管理员用户id
            post.setUserId(1764584057896873986L);
            Post isInsert = getIsInsert(tempRecord.getStr("title"));
            if (isInsert == null){
                //当数据库不存在这个数据时，才选择进行插入
                postList.add(post);
            }
        }
        //插入到我们的数据库当中（帖子表）
        boolean saveBatch = postService.saveBatch(postList);
        if (!saveBatch){
            throw new RuntimeException("数据保存失败");
        }
        log.info("帖子列表数据已初始化成功，条数：",postList.size());
    }



    private Post getIsInsert(String title) {
        PostQueryRequest postQueryRequest = new PostQueryRequest();
        postQueryRequest.setTitle(title);
        QueryWrapper<Post> queryWrapper = postService.getQueryWrapper(postQueryRequest);
        Post isInsert = postService.getOne(queryWrapper);
        return isInsert;
    }

}
